package com.lc.zpyh.ui.activity.order;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.lc.base.BaseDialog;
import com.lc.zpyh.R;
import com.lc.zpyh.app.AppActivity;
import com.lc.zpyh.http.glide.GlideApp;
import com.lc.zpyh.http.request.CancelOrdereApi;
import com.lc.zpyh.http.request.OrderDetailApi;
import com.lc.zpyh.http.request.RefundOrderApi;
import com.lc.zpyh.http.request.ReimburseApi;
import com.lc.zpyh.http.request.ReimburseBean;
import com.lc.zpyh.http.response.CancelOrdereBean;
import com.lc.zpyh.http.response.DetailBean;
import com.lc.zpyh.http.response.RefundOrderBean;
import com.lc.zpyh.other.IntentKey;
import com.lc.zpyh.ui.activity.supermarket.BusinessActivity;
import com.lc.zpyh.ui.activity.supermarket.PayActivity;
import com.lc.zpyh.ui.dialog.MessageDialog;
import com.lc.zpyh.util.BigDecimalUtils;
import com.lc.zpyh.util.SPUtil;
import com.lc.zpyh.util.constant.EvenConstant;
import com.lc.zpyh.util.eventbus.Event;
import com.lc.zpyh.view.ShopPhomeDialog;

import org.jetbrains.annotations.NotNull;

import java.text.DecimalFormat;

import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class OrderDetailsActivity extends AppActivity {
    @BindView(R.id.tv_countdown)
    TextView tvCountdown;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.tv_people)
    TextView tvPeople;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_total_price)
    TextView tvTotalPrice;
    @BindView(R.id.tv_yunfei)
    TextView tvYunfei;
    @BindView(R.id.tv_final_price)
    TextView tvFinalPrice;
    @BindView(R.id.tv_order_tag)
    TextView tvOrderTag;
    @BindView(R.id.tv_copy)
    TextView tvCopy;
    @BindView(R.id.tv_1)
    TextView tv1;
    @BindView(R.id.tv_order_time)
    TextView tvOrderTime;
    @BindView(R.id.btn_status)
    TextView btnStatus;
    @BindView(R.id.nestedscrollview)
    NestedScrollView nestedscrollview;
    @BindView(R.id.tv_shangjiamingcheng)
    TextView tv_shangjiamingcheng;
    @BindView(R.id.tv_beizhu)
    TextView tv_beizhu;
    @BindView(R.id.rv_shitang)
    RecyclerView rv_shitang;
    @BindView(R.id.tv_coupon)
    TextView tvCoupon;
    @BindView(R.id.pay_layout)
    RelativeLayout payLayout;
    @BindView(R.id.flow_layout)
    RelativeLayout flowLayout;
    @BindView(R.id.tv_pay_time)
    TextView tvPayTime;
    @BindView(R.id.tv_flow_no)
    TextView tvFlowNo;
    @BindView(R.id.add_layout)
    RelativeLayout addLayout;
    @BindView(R.id.tv_add_time)
    TextView tvAddTime;
    @BindView(R.id.tv_order_tv_yuyue)
    TextView tvOrderTvYuyue;
    private String order_id = "";
    private String system_id;
    private String sjdh;
    private String actualAmountPaid;
    private long difference;
    private CountDownTimer timer;
    private int statustpye;
    private String gjglysjh;
    private String sjsjh;
    private int state;
    private String orderNumber;
    private String merchantId;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_orderdetails;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        Intent intent = getIntent();
        order_id = intent.getStringExtra("orderid");
        system_id = intent.getStringExtra("system_id");
        orderNumber = intent.getStringExtra("orderNumber");

        merchantId= intent.getStringExtra("merchantId");
        if (intent.getStringExtra("difference") != null) {
            difference = Long.valueOf(intent.getStringExtra("difference"));
        }

        ;
        switch (system_id) {
            case "0":
                btnStatus.setText("立即支付");
                break;
            case "2":
                if (difference > 0) {


                    timer = new CountDownTimer(difference, 1000) {

                        @Override
                        public void onTick(long l) {
                            if (l > 120000) {
                                btnStatus.setClickable(false);

                                DecimalFormat dec = new DecimalFormat("##.##");

                                btnStatus.setText("0" + (int) Math.floor((l - 120000) / 60000) + ":" + dec.format(((l - 120000) % 60000) / 1000) + "秒后允许退款");

                                btnStatus.setBackgroundResource(R.color.white);
                                btnStatus.setTextColor(getResources().getColor(R.color.color666666));


                            } else if (l < 120000) {
                                statustpye = 1;
                                btnStatus.setClickable(true);


                                btnStatus.setText("申请退款");

                                btnStatus.setBackgroundResource(R.drawable.bg_pay_white);
                                btnStatus.setTextColor(getResources().getColor(R.color.colorec6a0d));
                            } else {
                                statustpye = 2;
                                btnStatus.setClickable(true);


                                btnStatus.setText("联系商家");

                                btnStatus.setBackgroundResource(R.drawable.bg_pay_white);
                                btnStatus.setTextColor(getResources().getColor(R.color.colorec6a0d));
                            }


                        }

                        @Override
                        public void onFinish() {
                            btnStatus.setClickable(true);
                            statustpye = 2;

                            btnStatus.setText("联系商家");

                            btnStatus.setBackgroundResource(R.drawable.bg_pay_white);
                            btnStatus.setTextColor(getResources().getColor(R.color.colorec6a0d));
//
                            timer.start();
                        }
                    };
                    timer.start();

                } else {
                    btnStatus.setClickable(true);

                    statustpye = 2;
                    btnStatus.setText("联系商家");

                    btnStatus.setBackgroundResource(R.drawable.bg_pay_white);
                    btnStatus.setTextColor(getResources().getColor(R.color.colorec6a0d));
                }


                break;
            case "3":
                break;
            case "4":
                btnStatus.setText("联系小哥");
                break;
            case "5":
                break;
            case "6":
                btnStatus.setText("评价");
                break;
            case "10":
                btnStatus.setVisibility(View.GONE);
                break;
        }
        getOrderDetail();
    }

    private void getOrderDetail() {
        EasyHttp.post(this).api(new OrderDetailApi().setOrderid(order_id))
                .request(new HttpCallback<DetailBean>(this) {
                    @Override
                    public void onSucceed(DetailBean data) {
                        //订单状态(0未支付,1支付成功,2配餐中,4配送中,5已存柜,6已接收,7已失效,8已删除(用户不可见))9 无柜存餐待确认 10 已取消 11 失效已取出12支付失败
                        state = data.getList().getOrderState();
                        if (state != 0) {
//                            payLayout.setVisibility(View.VISIBLE);
//                            flowLayout.setVisibility(View.VISIBLE);
                            tvPayTime.setText(data.getList().getOrderPaymentTime());
                            tvFlowNo.setText(data.getList().getPaymentOrder());
                        } else {
                            payLayout.setVisibility(View.GONE);
                            flowLayout.setVisibility(View.GONE);
                        }
                        if (state == 4 || state == 5 || state == 6 || state == 9 || state == 11) {
//                            addLayout.setVisibility(View.VISIBLE);
                            tvAddTime.setText(data.getList().getCateringFinishTime());
                        } else {
                            addLayout.setVisibility(View.GONE);
                        }
                            if (state==10||state==12||state==13||state==14){
                                btnStatus.setVisibility(View.GONE);
                            }
                        if (data.getList().getAppointmentTime()==null){
                            tvOrderTvYuyue.setText("尽快送达");
                        }else {
                            tvOrderTvYuyue.setText(data.getList().getAppointmentTime());
                        }

                        tvStatus.setText(getType(data.getList().getOrderState()));
                        tv_shangjiamingcheng.setText(data.getList().getSjmc());
                        tvPeople.setText(data.getList().getShr());
                        tv_beizhu.setText(data.getList().getOrderNote());
                        tvAddress.setText(data.getList().getGjmc());
                        tvOrderTime.setText(data.getList().getPlaceOrderTime());
                        tvOrderTag.setText(data.getList().getOrderNumber());
//                        actualAmountPaid = BigDecimalUtils.div(data.getList().getActualAmountPaid()+"","100",2)+"";
                        actualAmountPaid = BigDecimalUtils.add(BigDecimalUtils.div(data.getList().getActualAmountPaid() + "", "100", 2), BigDecimalUtils.div(data.getList().getOrderFreight() + "", "100", 2), 2);
                        tvFinalPrice.setText("￥" + BigDecimalUtils.add(BigDecimalUtils.div(data.getList().getActualAmountPaid() + "", "100", 2), BigDecimalUtils.div(data.getList().getFreightProportion() + "", "100", 2), 2));
                        tvTotalPrice.setText("￥" + BigDecimalUtils.div(data.getList().getOrderPrice() + "", "100", 2));
                        tvCoupon.setText("-￥" + BigDecimalUtils.div(data.getList().getCouponDiscountAmount() + "", "100", 2));
                        sjdh = data.getList().getShdh();
                        gjglysjh = data.getList().getGjglysjh();
                        sjsjh = data.getList().getSjsjh();
                        tvPhone.setText(data.getList().getShdh());
                        tvYunfei.setText("￥" + BigDecimalUtils.div(data.getList().getFreightProportion() + "", "100", 2));
                        BaseQuickAdapter<DetailBean.OrderDetailsListDTO, BaseViewHolder> sjadapter = new BaseQuickAdapter<DetailBean.OrderDetailsListDTO, BaseViewHolder>(R.layout.item_shop_confirm_shangjia_order, data.getList().getOrderDetailsList()) {
                            @Override
                            protected void convert(@NotNull BaseViewHolder baseViewHolder, DetailBean.OrderDetailsListDTO bean) {

                                GlideApp.with(getActivity())
                                        .load(IntentKey.ORDER_IMAGE + bean.getMainImg())
                                        .transform(new MultiTransformation<>(new CenterCrop(), new CircleCrop()))
                                        .into((ImageView) baseViewHolder.getView(R.id.img_dianpu));
                                baseViewHolder.setText(R.id.goods, bean.getCommodityName());

                                if (bean.getSpecificationName()==null){
                                    String condimentsName;
                                    if (bean.getCondimentsName()==null){
                                        condimentsName="";

                                    }else {
                                        condimentsName= bean.getCondimentsName();
                                    }
                                    baseViewHolder.setText(R.id.tv_yueshou,"默认"+"  "+condimentsName);
                                }else {
                                    String condimentsName;
                                    if (bean.getCondimentsName()==null){
                                        condimentsName="";

                                    }else {
                                        condimentsName= bean.getCondimentsName();
                                    }
                                    baseViewHolder.setText(R.id.tv_yueshou,bean.getSpecificationName()+"  "+condimentsName);
                                }


                                baseViewHolder.setText(R.id.tv_xianjia, "￥" + BigDecimalUtils.div(bean.getCommodityPrice() + "", "100", 2));
                                baseViewHolder.setText(R.id.tv_num, "X" + bean.getCount());
                            }
                        };
                        rv_shitang.setAdapter(sjadapter);

                        ((BaseQuickAdapter<DetailBean.OrderDetailsListDTO, BaseViewHolder>) rv_shitang.getAdapter()).setOnItemClickListener((baseQuickAdapter, view, i) -> {

                            startActivity(new Intent(getContext(), BusinessActivity.class).putExtra("id",merchantId+""));
                        });
                    }


                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                    }
                });
    }
    /**
     *  退款和取消订单
     */
    private void reimburse(String orderid) {
        EasyHttp.post(this)
                .api(new ReimburseApi().setOrderid(orderid)).request(new HttpCallback<ReimburseBean>(this) {

            @Override
            public void onSucceed(ReimburseBean data) {


                if (data.isSuccess()){
                    toast("退款成功");
                    finish();
                }else {
                    toast(data.getMsg());
                }
            }
            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }
    private void refundOrder(String orderid) {
        EasyHttp.post(this)
                .api(new RefundOrderApi().setOrderid(orderid)).request(new HttpCallback<RefundOrderBean>(this) {

            @Override
            public void onSucceed(RefundOrderBean data) {
                if (data.getSuccess() != null) {
                    finish();
                } else {
                    toast("无法退款");
                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    private void cancelOrder(String orderid) {
        EasyHttp.post(this)
                .api(new CancelOrdereApi().setOrderNum(orderid).setUserId(SPUtil.get(getContext(), IntentKey.USERID, ""))).request(new HttpCallback<CancelOrdereBean>(this) {

            @Override
            public void onSucceed(CancelOrdereBean data) {
//                if (data.isSuccess()){
//                    getOrderList();
//                }else {
//                    toast(data.getMsg());
//                }
            }

            @Override
            public void onFail(Exception e) {
                super.onFail(e);

            }
        });
    }

    @OnClick({R.id.btn_status, R.id.tv_copy,R.id.tv_shangjiamingcheng})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_status:
                switch (system_id) {
                    case "0":
//                       支付
                        startActivity(new Intent(this, PayActivity.class).putExtra("orderId", order_id).putExtra("actualAmountPaid", actualAmountPaid).putExtra("orderNumber",orderNumber));
                        break;
                    case "2":
                        if (statustpye == 2) {
                            ShopPhomeDialog ShopPhomeDialog = new ShopPhomeDialog(this, "联系商家", sjsjh);
                            ShopPhomeDialog.show();
                        } else {
                            // 消息对话框
                            new MessageDialog.Builder(getActivity())
                                    // 标题可以不用填写
                                    .setTitle("申请退款")
                                    // 内容必须要填写
                                    .setMessage("是否要申请退款？")
                                    // 确定按钮文本
                                    .setConfirm(getString(R.string.common_confirm))
                                    // 设置 null 表示不显示取消按钮
                                    .setCancel(getString(R.string.common_cancel))
                                    // 设置点击按钮后不关闭对话框
                                    //.setAutoDismiss(false)
                                    .setListener(new MessageDialog.OnListener() {

                                        @Override
                                        public void onConfirm(BaseDialog dialog) {
                                            reimburse(order_id+"");
                                        }

                                        @Override
                                        public void onCancel(BaseDialog dialog) {
                                         dialog.dismiss();
                                        }
                                    })
                                    .show();

//                            refundOrder(order_id);
//                            cancelOrder(order_id);
                        }
                        break;
                    case "3":
                        break;
                    case "4":
                        ShopPhomeDialog ShopPhomeDialog1 = new ShopPhomeDialog(this, "联系小哥", gjglysjh);
                        ShopPhomeDialog1.show();
                        break;
                    case "5":
                        break;
                    case "6":
                        startActivity(new Intent(this, ShopCommentActivity.class).putExtra("order_id", order_id));

                        break;
                    case "7":
                        break;
                }

                break;
            case R.id.tv_copy:
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                // 将文本内容放到系统剪贴板里。
                cm.setText(tvOrderTag.getText());
                ToastUtils.show("复制成功");
                break;
            case R.id.tv_shangjiamingcheng:
                startActivity(new Intent(getContext(), BusinessActivity.class).putExtra("id",merchantId+""));
                break;
        }
    }

    private String getType(int type) {
        String res = "";//订单状态(0未支付,1支付成功,2配餐中,4配送中,5已存柜,6已接收,7已失效,8已删除(用户不可见))9 无柜存餐待确认 10 已取消 11 失效已取出12支付失败
        switch (type) {
            case 0:
                res = "待支付";
                break;
            case 1:
                res = "支付成功";
                break;
            case 2:
                res = "配餐中";
                break;
            case 3:
                res = "";
                break;
            case 4:
                res = "配送中";
                break;
            case 5:
                res = "已存柜";
                break;
            case 6:
                res = "已接收";
                break;
            case 7:
                res = "已失效";
                break;
            case 8:
                res = "已删除";
                break;
            case 9:
                res = "无柜存餐待确认";
                break;
            case 10:
                res = "已取消";
                break;
            case 11:
                res = "失效已取出";
                break;
            case 12:
                res = "支付失败";
                break;
        }
        return res;
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void receiveEvent(Event event) {
        super.receiveEvent(event);
        if (event.getCode() == EvenConstant.PAYSTAUTS) {
//
            finish();
        }
    }
}
